<template>
  <div>
    <!-- 用户导航页面 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 用户数据列表页面 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="10">
          <div class="grid-content bg-purple">
            <!-- 搜索框 -->
            <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUsersList">
              <el-button slot="append" icon="el-icon-search" @click="getUsersList"></el-button>
            </el-input>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="grid-content bg-purple">
            <!-- 按钮 -->
            <el-button type="primary" @click="adddialogVisible=true">添加用户</el-button>
          </div>
        </el-col>
      </el-row>
      <!-- 表格 -->
      <el-table :data="usersList" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <!--  会显示当前行的所有数据 -->
            <!-- {{scope.row}} -->
            <el-switch v-model="scope.row.mg_state" @change="usersStateChanged(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" style="width: 150px">
          <!-- 操作编辑按钮 -->
          <template slot-scope="scope">
            <el-row>
              <el-button
                type="primary"
                icon="el-icon-edit"
                circle
                size="mini"
                @click="editDialogShow(scope.row.id)"
              ></el-button>
              <el-button
                type="danger"
                icon="el-icon-delete"
                circle
                size="mini"
                @click="delUsers(scope.row.id)"
              ></el-button>
              <!-- 鼠标悬停有提示信息 -->
              <el-tooltip content="分配角色" :enterable="false">
                <el-button
                  type="warning"
                  icon="el-icon-setting"
                  circle
                  size="mini"
                  @click="setRolesBtn(scope.row)"
                ></el-button>
              </el-tooltip>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页功能 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 添加用户消息弹框 -->
    <el-dialog title="添加用户信息" :visible.sync="adddialogVisible" width="50%" @close="addDialogClosed">
      <!-- 内容主题区域  rules是验证规则，ref是引用相关的-->
      <el-form label-width="90px" :model="addUsers" :rules="addUsersRules" ref="addUsersRef">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUsers.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUsers.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUsers.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addUsers.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="adddialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUsersBtn">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑用户信息弹框 -->
    <el-dialog
      title="修改用户信息"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <!-- 内容主题区域  rules是验证规则，ref是重置相关的-->
      <el-form label-width="70px" :model="editUsers" :rules="editUsersRules" ref="editUsersRef">
        <el-form-item label="用户名">
          <el-input v-model="editUsers.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUsers.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editUsers.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUsersBtn">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 给用户分配角色 -->
    <el-dialog title="分配角色" :visible.sync="setRoleDialog" width="40%" @close="setRoleDialogClosed">
      <p>当前用户：{{userInfo.username}}</p>
      <p>当前角色：{{userInfo.role_name}}</p>
      <span>分配新角色：</span>
      <el-select v-model="roleSelectId" placeholder="请选择角色">
        <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialog = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleBtn">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    // 验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^\w+@\w+(\.\w+)+$/
      if (regEmail.test(value)) {
        return cb()
      }
      // 返回一个错误的提示
      this.$message.error('请输入合法的邮箱')
    }
    // 验证手机号码的规则
    var checkMobile = (rule, value, cb) => {
      const checkMobile = /^1[34578]\d{9}$/
      if (checkMobile.test(value)) {
        return cb()
      }
      // 返回一个错误的提示
      this.$message.error('请输入合法的电话号码')
    }
    return {
      queryInfo: {
        query: '',
        // pagenum当前页码 pagesize每页显示条数
        pagenum: 1,
        pagesize: 2
      },
      total: 0,
      usersList: [],
      // 添加用户消息弹框
      adddialogVisible: false,
      addUsers: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      addUsersRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            validator: checkEmail,
            message: '长度在 10 到 15 个字符',
            trigger: 'blur'
          }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, message: '长度11 个字符', trigger: 'blur' }
        ]
      },
      editDialogVisible: false,
      // 用户需要编辑的信息存放到这里
      editUsers: {},
      editUsersRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            validator: checkEmail,
            message: '长度在 10 到 15 个字符',
            trigger: 'blur'
          }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, message: '长度11 个字符', trigger: 'blur' }
        ]
      },
      // 分配角色
      setRoleDialog: false,
      userInfo: {},
      // 用户角色列表
      roleList: [],
      // 保存已选中角色的id
      roleSelectId: ''
    }
  },
  created() {
    this.getUsersList()
  },
  methods: {
    // 获取用户数据
    async getUsersList() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('res.meta.message')
      }
      this.total = res.data.total
      this.usersList = res.data.users
    },
    handleSizeChange(newSize) {
      // 每页显示条数改变的事件
      this.queryInfo.pagesize = newSize
      this.getUsersList()
    },
    handleCurrentChange(newPage) {
      // 当前页码数改变的事件
      this.queryInfo.pagenum = newPage
      this.getUsersList()
    },
    // 状态开关发生改变
    async usersStateChanged(info) {
      // console.log(info)
      const { data: res } = await this.$http.put(
        `users/${info.id}/state/${info.mg_state}`
      )
      // console.log(res)
      if (res.meta.status !== 200) {
        info.mg_state = !info.mg_state
        return this.$message.error('更新用户状态失败')
      }
      this.$message.success('更新用户状态成功')
    },
    // 当点击X时，重置表单
    addDialogClosed() {
      this.$refs.addUsersRef.resetFields()
    },
    // 点击确认时
    addUsersBtn() {
      this.$refs.addUsersRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('请填写完整的信息')
        }
        // console.log(valid)
        const { data: res } = await this.$http.post('users', this.addUsers)
        // console.log(res)
        if (res.meta.status !== 201) {
          return this.$message.error('添加用户失败，请重试')
        }
        this.$message.success('添加用户成功')
        // dialog框关闭
        this.adddialogVisible = false
        this.getUsersList()
      })
    },
    // 编辑用户
    async editDialogShow(id) {
      const { data: res } = await this.$http.get('users/' + id)
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户失败，请重试')
      }
      this.editUsers = res.data
      this.editDialogVisible = true
    },
    // 当点击编辑按钮的X号时，重置表单
    editDialogClosed() {
      this.$refs.editUsersRef.resetFields()
    },
    // 当点击确认是时候要先验证表单
    editUsersBtn() {
      this.$refs.editUsersRef.validate(async valid => {
        // console.log(valid)
        if (!valid) {
          return this.$message.error('请填写完整的用户信息')
        }
        const { data: res } = await this.$http.put(
          'users/' + this.editUsers.id,
          this.editUsers
        )
        if (res.meta.status !== 200) {
          return this.$message.error('用户修改失败，请重试')
        }
        this.$message.success('修改信息成功')
        this.getUsersList()
        this.editDialogVisible = false
        // console.log(res)
      })
    },
    // 删除用户
    async delUsers(id) {
      // 返回的是一个promise对象，所以可以用async和await来处理
      /* const res = this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      console.log(res) */
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => {
        return err
      })
      // 如果用户确认了删除，则返回值为字符串confirm
      // 如果用户取消了删除，则返回字符串cancel
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('不要慌，还没有删除')
      }
      const { data: res } = await this.$http.delete('users/' + id)
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('删除用户失败，可能是权限不够')
      }
      this.$message.success('删除用户成功')
      this.getUsersList()
    },
    // 为用户分配角色,并获取所有用户的角色
    async setRolesBtn(userInfo) {
      this.userInfo = userInfo
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户角色错误')
      }
      // console.log(res)
      // console.log(userInfo)
      this.roleList = res.data
      this.setRoleDialog = true
    },
    // 保存当前的更改
    async saveRoleBtn() {
      if (!this.roleSelectId) {
        return this.$message.error('还未选择角色')
      }
      const { data: res } = await this.$http.put(
        `users/${this.userInfo.id}/role`,
        {
          rid: this.roleSelectId
        }
      )
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('选择角色发生异常')
      }
      this.$message.success('选择角色成功')
      this.getUsersList()
      this.setRoleDialog = false
    },
    // 选择新角色成功后重置
    setRoleDialogClosed() {
      this.userInfo = {}
      this.roleSelectId = ''
    }
  }
}
</script>
<style lang="less" scoped>
</style>
